package com.pams.controller;

import cn.hutool.core.io.FileUtil;
import com.pams.context.BaseContext;
import com.pams.pojo.entity.FileEN;
import com.pams.pojo.entity.FileResponse;
import com.pams.result.Result;
import com.pams.service.FileService;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api")

public class FileController {

    @Autowired
   private FileService fileService ;
    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/upload")
    public ResponseEntity<List<FileResponse>> uploadFiles(
            @RequestParam("files") MultipartFile[] files) throws IOException {

        List<FileResponse> responses = new ArrayList<>();
        Path uploadPath = Paths.get(uploadDir);

        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String storedName = UUID.randomUUID() + extension;

            Path targetPath = uploadPath.resolve(storedName);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            responses.add(new FileResponse(
                    originalFilename,
                    storedName,
                    file.getSize(),
                    "http://localhost:8080/api/download/" + storedName
            ));

            FileEN theFile = new FileEN();
            theFile.setDownloadUrl("http://localhost:8080/api/download/" + storedName);
            theFile.setOriginalName(originalFilename);
            theFile.setSize(file.getSize());
            theFile.setStoredName(storedName);
            theFile.setType(file.getContentType());
            theFile.setUploadTime(LocalDateTime.from(LocalDateTime.now()));
            theFile.setUsername(BaseContext.getCurrentUsername());
            theFile.setType(file.getContentType());
            fileService.add(theFile);

        }

        return ResponseEntity.ok(responses);
    }

    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<Resource> downloadFile(
            @PathVariable String filename) throws IOException {


        // 2. 构建文件路径
        Path filePath = Paths.get(uploadDir).resolve(filename).normalize();
        Resource resource = new UrlResource(filePath.toUri());

        // 3. 验证文件存在且可读
        if (!resource.exists() || !resource.isReadable()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ByteArrayResource("FileEN not found".getBytes()));
        }

        // 4. 获取原始文件名（根据你的存储逻辑可能需要从数据库获取）
       // String originalFilename = getOriginalFilename(filename); // 需要实现该方法
        String originalFilename = UUID.randomUUID().toString();
        // 5. 设置响应头
        return ResponseEntity.ok()
                // 解决中文文件名乱码问题
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename*=UTF-8''" + URLEncoder.encode(originalFilename, "UTF-8").replace("+", "%20"))
                // 准确设置Content-Type
                .contentType(MediaType.parseMediaType(Files.probeContentType(filePath)))
                // 缓存控制
                .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
                .header(HttpHeaders.PRAGMA, "no-cache")
                .header(HttpHeaders.EXPIRES, "0")
                .body(resource);
    }


    @GetMapping("/file/list")
    public Result<List<FileEN>> getFileList(){
        List<FileEN> list =  fileService.getList();
        return Result.success(list);
    }

    @PutMapping("/file/deleteOne")
    public Result deleteOne(@RequestBody FileEN fileEN){
        fileService.deleteOne(fileEN);
        Path filePath = Paths.get(uploadDir).resolve(fileEN.getStoredName()).normalize();

        FileUtil.del(filePath);
        return Result.success();
    }

}



